<?php

namespace api\web\controller;

use Firebase\JWT\Key;
use Firebase\JWT\JWT;
use think\facade\Request;
use cmf\controller\RestBaseController;
use think\facade\Db;

class MoneyController extends RestBaseController
{
    public function money($request){
        $money = input('money') ;
        if(! $money){
            $this->error('没有输入钱');
        }
        $user=Db::name('member')
        ->where('id',$request()->user)
        ->inc('wallet',$money)
        ->update();
        //添加流水记录
//        insert_data=[];
    }
    // 充值功能
    public function addMoney()
    {
        $data = input('post.');
        $token = Request::header();

        if (!isset($token['token']) || empty($token['token'])) {
            $this->error('缺少token');
        }

        $key = new Key(config('app.jwt_key'), 'HS256');

        Db::startTrans();

        try {
            $res = JWT::decode($token['token'], $key);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        $user_id = $res->data->user_id;
        // 获取充值金额
        $money = $data['money'];
        $reason = $data['reason'] ?? '充值';

        try {
            // 调用 common 函数处理充值逻辑
            $newBalance = add_money_log($user_id, $money, $reason, 1);
            Db::commit();
            return json(['status' => 'success', 'message' => '充值成功', 'new_balance' => $newBalance]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }
    // 查询流水记录
    public function GetMoney()
    {
        $token = Request::header();

        if (!isset($token['token']) || empty($token['token'])) {
            $this->error('缺少token');
        }

        $key = new Key(config('app.jwt_key'), 'HS256');

        try {
            $res = JWT::decode($token['token'], $key);
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $user_id = $res->data->user_id;

        try {
            // 调用 common 函数查询流水记录
            $logs = Getmoney($user_id);
            return json(['status' => 'success', 'logs' => $logs]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }
}